cap program drop jkf_gen
program define jkf_gen
syntax varlist [, BYvariable(varlist) STandardize(string) PREfix(string) SUFFix(string) QUANT(string) QUANTVAL(string) QUANTBY(string) REMOVE(string)]

if "`prefix'"=="" {
  local prefix "amb"
}
if "`suffix'"=="" {
  local suffix = "global_i"
}
if "`quantby'"=="" {
  local quantby "diag_year"
}

foreach x of local varlist {
  cap drop `prefix'_`x'_`suffix'
  if "`standardize'" != "" {
    cap drop `prefix'_`x'`standardize'_`suffix'
    cap drop o_`x'
    cap drop m_`x'
    cap drop sd_`x'
    rename `x' o_`x'
    egen m_`x' = mean(o_`x') , by(`byvariable')
    egen sd_`x' = sd(o_`x'), by(`byvariable')
    gen `x' = (o_`x'-m_`x')/(`standardize'*sd_`x')
  }
    if "`quant'"!="" {
      cap drop g_`x'
      cap drop qval_`x'
      egen g_`x' = group(`quantby') if `x'!=.
      qui levelsof g_`x', clean local(groups)
      gen qval_`x' = 0
      gen q_`x' = .
      foreach g of local groups {
        xtile q2_`x' = `x' if g_`x'==`g', nq(`quant')
        replace q_`x' = q2_`x' if g_`x'==`g' & `x'!=.
        drop q2_`x'
      }
      foreach v of local quantval {
        replace qval_`x' = 1 if q_`x'==`v'
      }
      rename `x' temp_`x'
      rename qval_`x' `x'
    }

  if "`remove'"=="" {
    cap drop s_`x'
    egen s_`x' = sum(`x'), by(`byvariable')
    cap drop denom0
    gen denom0 = 1 if `x'!=.
    egen denom = sum(denom0), by(`byvariable')
    gen `prefix'_`x'_`suffix' = (s_`x' - `x')/(denom-1)
  }
  if "`remove'"!="" {
    cap drop s_`x'
    cap drop sr_`x'
    egen s_`x' = sum(`x'), by(`byvariable')
    egen sr_`x' = sum(`x'), by(`byvariable' `remove')
    cap drop denom0
    cap drop denomr
    gen denom0 = 1 if `x'!=.
    egen denom = sum(denom0), by(`byvariable')
    egen denomr = sum(denom0), by(`byvariable' `remove')    
    gen `prefix'_`x'_`suffix' = (s_`x' - sr_`x')/(denom-denomr)
  }
  
  drop s_`x' denom0 denom
  if "`standardize'"!="" {
    drop m_`x'
    drop sd_`x'
    drop `x'
    rename o_`x' `x'
    rename `prefix'_`x'_`suffix' `prefix'_`x'`standardize'_`suffix'
  }
  if "`quant'"!="" {
    rename `x' qval_`x'
    rename temp_`x' `x'
    cap drop q_`x'
    cap drop g_`x'
    cap drop qval_`x'
  }
}


end
                
